package com.luo.jiuyuetest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luo.jiuyuetest.dto.PageResult;
import com.luo.jiuyuetest.dto.PartInfoDTO;
import com.luo.jiuyuetest.entity.Product;
import com.luo.jiuyuetest.entity.Productpart;
import com.luo.jiuyuetest.entity.Supplier;
import com.luo.jiuyuetest.mapper.ProductMapper;
import com.luo.jiuyuetest.mapper.ProductpartMapper;
import com.luo.jiuyuetest.mapper.SupplierMapper;
import com.luo.jiuyuetest.service.ProductpartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luozhibin
 * @since 2025-11-04
 */
@Service
public class ProductpartServiceImpl extends ServiceImpl<ProductpartMapper, Productpart> implements ProductpartService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductpartMapper productpartMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 更新指定产品类型下的指定零件类型成本翻倍
     * @param productCategory 产品分类
     * @param partCategory 零件分类
     * @return 更新结果消息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updatePartCostByCategory(String productCategory, String partCategory) {
        // 1. 查询指定类型的产品列表
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("category", productCategory);
        List<Product> products = productMapper.selectList(productQueryWrapper);

        if (products == null || products.isEmpty()) {
            return "未找到产品类型为【" + productCategory + "】的产品";
        }

        // 2. 获取产品ID列表
        List<Integer> productIds = products.stream()
                .map(Product::getId)
                .collect(Collectors.toList());

        System.out.println("找到产品数量: " + products.size() + ", ID列表: " + productIds);

        // 3. 查询这些产品下指定类型的零件
        QueryWrapper<Productpart> partQueryWrapper = new QueryWrapper<>();
        partQueryWrapper.in("pid", productIds)
                .eq("category", partCategory);
        List<Productpart> parts = productpartMapper.selectList(partQueryWrapper);

        if (parts == null || parts.isEmpty()) {
            return "未找到产品类型为【" + productCategory + "】且零件类型为【" + partCategory + "】的零件";
        }

        System.out.println("找到零件数量: " + parts.size());

        // 4. 遍历零件，成本翻倍并更新
        int updateCount = 0;
        for (Productpart part : parts) {
            BigDecimal oldCost = part.getCost();
            BigDecimal newCost = oldCost.multiply(new BigDecimal("2"));

            part.setCost(newCost);
            productpartMapper.updateById(part);

            System.out.println("零件ID: " + part.getId() + ", 名称: " + part.getName()
                    + ", 原成本: " + oldCost + ", 新成本: " + newCost);
            updateCount++;
        }

        return "成功更新 " + updateCount + " 个零件的成本（产品类型: " + productCategory
                + ", 零件类型: " + partCategory + "）";
    }
    /**
     * 查询指定供应商下的指定产品类型的所有零件（带分页、排序）
     * @param supplierName 供应商名称
     * @param productCategory 产品类型
     * @param pageNum 当前页码
     * @param pageSize 每页数量
     * @return 分页结果
     */
    @Override
    public PageResult<PartInfoDTO> selectPartsByCondition(String supplierName, String productCategory, Integer pageNum, Integer pageSize) {
        System.out.println("=== 开始查询零件 ===");
        System.out.println("供应商名称: " + supplierName);
        System.out.println("产品类型: " + productCategory);
        System.out.println("页码: " + pageNum + ", 每页数量: " + pageSize);

        // 1. 查询供应商
        QueryWrapper<Supplier> supplierWrapper = new QueryWrapper<>();
        supplierWrapper.eq("name", supplierName);
        Supplier supplier = supplierMapper.selectOne(supplierWrapper);

        if (supplier == null) {
            System.out.println("未找到供应商: " + supplierName);
            return new PageResult<>(new ArrayList<>(), 0L, 0L, (long) pageNum, (long) pageSize);
        }

        System.out.println("找到供应商，Code: " + supplier.getCode());

        // 2. 查询该供应商下指定类型的产品
        QueryWrapper<Product> productWrapper = new QueryWrapper<>();
        productWrapper.eq("suppliercode", supplier.getCode())
                .eq("category", productCategory);
        List<Product> products = productMapper.selectList(productWrapper);

        if (products == null || products.isEmpty()) {
            System.out.println("未找到符合条件的产品");
            return new PageResult<>(new ArrayList<>(), 0L, 0L, (long) pageNum, (long) pageSize);
        }

        // 3. 获取产品ID列表
        List<Integer> productIds = products.stream()
                .map(Product::getId)
                .collect(Collectors.toList());

        System.out.println("找到产品数量: " + products.size() + ", ID列表: " + productIds);

        // 4. 分页查询这些产品的零件，并按成本降序排序
        Page<Productpart> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Productpart> partWrapper = new QueryWrapper<>();
        partWrapper.in("pid", productIds)
                .orderByDesc("cost");  // 按成本从高到低排序

        Page<Productpart> partPage = productpartMapper.selectPage(page, partWrapper);

        System.out.println("查询到零件总数: " + partPage.getTotal());
        System.out.println("当前页零件数: " + partPage.getRecords().size());

        // 5. 转换为 DTO
        List<PartInfoDTO> partInfoList = new ArrayList<>();
        for (Productpart part : partPage.getRecords()) {
            PartInfoDTO dto = new PartInfoDTO();
            BeanUtils.copyProperties(part, dto);
            partInfoList.add(dto);
        }

        // 6. 封装分页结果
        PageResult<PartInfoDTO> result = new PageResult<>(
                partInfoList,
                partPage.getTotal(),
                partPage.getPages(),
                partPage.getCurrent(),
                partPage.getSize()
        );

        System.out.println("=== 查询完成 ===");
        return result;
    }
}